package com.outsourcing.bottle.ui;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.os.Process;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.ext.SatelliteMenu;
import android.view.ext.SatelliteMenu.SateliteClickedListener;
import android.view.ext.SatelliteMenuItem;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.adapter.PublicActivityAdapter;
import com.outsourcing.bottle.adapter.TabAdapter;
import com.outsourcing.bottle.db.LoginUserInfoTable;
import com.outsourcing.bottle.domain.BottleTimelineInfo;
import com.outsourcing.bottle.domain.LoginUserInfo;
import com.outsourcing.bottle.domain.LoginUserInfoEntry;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.ServiceUtils;
import com.outsourcing.bottle.util.TextUtil;
import com.outsourcing.bottle.util.UICore;

public class HomeOldActivity extends BasicActivity implements Callback, OnClickListener {

	private final int EXEU_GET_TIMELINE = 0;

	private final int menu_exprofile = 4;
	private final int menu_exphoto = 3;
	private final int menu_gainbt = 2;
	private final int menu_sendbt = 1;
	
	private ImageView backView;
	private ImageButton menuView;

	private Gallery gallery = null;
	private TabAdapter textAdapter;
	private static final String[] TAB_NAMES = { "Exchange", "Bottle", "BTfriend" };
	private ListView listView = null;
	private HomeOldActivity context = null;
	private Handler handler = null;

	BottleTimelineInfo bottlelist = null;

	// ----------------------Gallery用到的常量-----------------------------
	private int showingIndex = -1;
	private static final int TIME_OUT_DISPLAY = 300;
	private int toShowIndex = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;

		handler = new Handler(this);

		TextUtil.setCtxForGetResString(context);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.home);

		initLayout();
		initLikePopupWindow();
		
		UICore.eventTask(this, this, EXEU_GET_TIMELINE, getString(R.string.init_data), null);
	}

	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case EXEU_GET_TIMELINE:
			getLoginUserInfo();
			getTimeLine();
			break;

		default:
			break;
		}
	}
	
	/**
	 * 获取用户基本资料
	 */
	private void getLoginUserInfo(){
		StringBuffer url = new StringBuffer(UrlConfig.get_loginuser_info);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());

		ServiceUtils.dout("login url:"+url.toString());
		
		try {
			String result = HttpUtils.doGet(url.toString());
			Gson gson = new Gson();
			LoginUserInfo loginUserInfo = gson.fromJson(result,
					LoginUserInfo.class);

			LoginUserInfoTable loginUserInfoTable = new LoginUserInfoTable();
			if (null != loginUserInfoTable.getLoginUserInfo(AppContext
					.getInstance().getLogin_uid())) {
				loginUserInfoTable.deleteLoginUserInfoById(AppContext
						.getInstance().getLogin_uid());
				loginUserInfoTable.saveLoginUserInfo(loginUserInfo
						.getLoginuser_info(), AppContext.getInstance()
						.getLogin_uid());
			}else {
				loginUserInfoTable.saveLoginUserInfo(loginUserInfo
						.getLoginuser_info(), AppContext.getInstance()
						.getLogin_uid());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void getTimeLine() {
		StringBuffer url = new StringBuffer(UrlConfig.get_bt_timeline);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&mode=0");
		url.append("&count=20");
		url.append("&page=1");
		url.append("&likescount=10");
		url.append("&feedscount=5");
		ServiceUtils.dout("timeline url:"+url.toString());
		
		try {
			String result = HttpUtils.doGet(url.toString());

			System.out.println("result:" + result);

			Gson gson = new Gson();
			long firstTime = System.currentTimeMillis();
			bottlelist = gson.fromJson(result, BottleTimelineInfo.class);

			ServiceUtils.dout("wastTime:"
					+ (System.currentTimeMillis() - firstTime));

			Message message = Message.obtain(handler);
			message.what = EXEU_GET_TIMELINE;
			handler.sendMessage(message);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 喜欢瓶子的操作
	 * @param btId     瓶子ID 
	 * @param likeType 喜欢or不喜欢  <---> 1 or 2
	 */
	private void likeOperation(int btId,int likeType){
		StringBuffer url = new StringBuffer(UrlConfig.likeop_bt);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&btid="+btId);
		url.append("&liketype="+likeType);
		ServiceUtils.dout("lokeOperation url:"+url.toString());
		
		try {
			String results = HttpUtils.doGet(url.toString());
			ServiceUtils.dout("lokeOperation result:"+results);
			if (null!=results) {
				JSONObject obj = new JSONObject(results);
				JSONObject resultObj = obj.getJSONObject("results");
				int success = resultObj.getInt("success");	
				String errmsg = resultObj.getString("errmsg");
				String successmsg = resultObj.getString("successmsg");
				if (success == 1) {
					onToast(successmsg);
				}else {
					onToast(errmsg);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void openBottle(int btId){
		StringBuffer url = new StringBuffer(UrlConfig.open_bt);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&btid="+btId);
		ServiceUtils.dout("openBottle url:"+url.toString());
		
		try {
			String results = HttpUtils.doGet(url.toString());
			ServiceUtils.dout("openBottle result:"+results);
			if (null!=results) {
				JSONObject obj = new JSONObject(results);
				JSONObject resultObj = obj.getJSONObject("results");
				int success = resultObj.getInt("success");	
				String errmsg = resultObj.getString("errmsg");
				String successmsg = resultObj.getString("successmsg");
				if (success == 1) {
					
					StringBuffer mSingleBottleUrl = new StringBuffer(UrlConfig.get_bt_timeline);
					mSingleBottleUrl.append("?mode=4&bit="+btId);
					ServiceUtils.dout("get open bottle url:"+mSingleBottleUrl.toString());
					
					
					
					onToast(successmsg);
				}else {
					onToast(errmsg);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	private void dropBottle(int btId){
		StringBuffer url = new StringBuffer(UrlConfig.discard_bt);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&btid="+btId);
		ServiceUtils.dout("dropBottle url:"+url.toString());
		
		try {
			String results = HttpUtils.doGet(url.toString());
			ServiceUtils.dout("dropBottle result:"+results);
			if (null!=results) {
				JSONObject obj = new JSONObject(results);
				JSONObject resultObj = obj.getJSONObject("results");
				int success = resultObj.getInt("success");	
				String errmsg = resultObj.getString("errmsg");
				String successmsg = resultObj.getString("successmsg");
				if (success == 1) {
					onToast(successmsg);
				}else {
					onToast(errmsg);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void initLayout() {

		gallery = (Gallery) findViewById(R.id.gallery);
		gallery.setFocusable(true);
		gallery.requestFocus();
		gallery.requestFocusFromTouch();
		gallery.setClickable(true);
		textAdapter = new TabAdapter(this, Arrays.asList(TAB_NAMES));
		gallery.setAdapter(textAdapter);
		gallery.setSelection(34);
		gallery.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				TabAdapter adapter = (TabAdapter) parent.getAdapter();
				adapter.setSelectedTab(position);
				System.out
						.println("onItemClick:" + position % TAB_NAMES.length);
				switch (position % TAB_NAMES.length) {
				case 0:
					break;
				case 1:
					break;
				case 2:
					break;
				}
			}
		});

		gallery.setOnItemSelectedListener(new Gallery.OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View arg1,
					int position, long arg3) {

				// --------------------------------------------------
				toShowIndex = position;
				final Handler handler = new Handler() {
					@Override
					public void handleMessage(Message msg) {
						if (showingIndex != toShowIndex) {
							showingIndex = toShowIndex;

							System.out.println("position:" + toShowIndex % 3);
							// 业务逻辑处理
						}
					}
				};
				Thread checkChange = new Thread() {
					@Override
					public void run() {
						int myIndex = toShowIndex;
						try {
							sleep(TIME_OUT_DISPLAY);
							if (myIndex == toShowIndex) {
								handler.sendEmptyMessage(0);
							}
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				};

				checkChange.start();

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				System.out.println("NothingSelected");
			}
		});
		
		
		listView = (ListView) findViewById(R.id.list_view);
		
		
		SatelliteMenu menu = (SatelliteMenu) findViewById(R.id.menu);
		List<SatelliteMenuItem> items = new ArrayList<SatelliteMenuItem>();
		items.add(new SatelliteMenuItem(menu_exprofile, R.drawable.menu_exprofile));
		items.add(new SatelliteMenuItem(menu_exphoto, R.drawable.menu_exphoto));
		items.add(new SatelliteMenuItem(menu_gainbt, R.drawable.menu_gainbt));
		items.add(new SatelliteMenuItem(menu_sendbt, R.drawable.menu_sendbt));
		menu.addItems(items);
		menu.setOnItemClickedListener(new SateliteClickedListener() {

			public void eventOccured(int id) {
				switch (id) {
				case menu_sendbt:
					new Thread(){
						public void run() {
							try {
								Thread.sleep(500);
								Intent throwIntent = new Intent(HomeOldActivity.this, ChooseBottleActivity.class);
								throwIntent.putExtra("type", "throw");
								startActivity(throwIntent);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						};
					}.start();
					break;
				case menu_gainbt:
					new Thread(){
						public void run() {
							try {
								Thread.sleep(500);
								Intent tryIntent = new Intent(HomeOldActivity.this, ChooseBottleActivity.class);
								tryIntent.putExtra("type", "try");
								startActivity(tryIntent);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						};
					}.start();
					break;
				case menu_exphoto:
					break;
				case menu_exprofile:
					break;
				default:
					break;
				}
			}
		});

		backView = (ImageView) findViewById(R.id.topbar_back);
		backView.setOnClickListener(this);
		menuView = (ImageButton) findViewById(R.id.topbar_menu);
		menuView.setOnClickListener(this);
	}

	PublicActivityAdapter chatHistoryAdapter;

	private void setAdapterForThis() {
		// List<BottleEntry> messages = new ArrayList<BottleEntry>();
		// messages.add(new BottleEntry(R.drawable.headphoto,
		// R.drawable.btn_sendbt));
		// messages.add(new BottleEntry(R.drawable.headphoto,
		// R.drawable.btn_profile));
		// messages.add(new BottleEntry(R.drawable.headphoto,
		// R.drawable.btn_gainbt));
		// messages.add(new BottleEntry(R.drawable.headphoto,
		// R.drawable.bottle_type_1));
		// messages.add(new BottleEntry(R.drawable.headphoto,
		// R.drawable.bottle_type_2));

		if (null != bottlelist) {
			
			View mheaderView = LayoutInflater.from(this).inflate(R.layout.bottle_list_header, null);
			RelativeLayout mThrowBottle = (RelativeLayout)mheaderView.findViewById(R.id.rl_tlime_throw_bottle);
			RelativeLayout mGainBottle = (RelativeLayout)mheaderView.findViewById(R.id.rl_tlime_gain_bottle);
			RelativeLayout mProfileInfo = (RelativeLayout)mheaderView.findViewById(R.id.rl_tlime_profile_bottle);
			
			if (bottlelist.getShowtips().getShow_sendbt_tips()==1) {
				mThrowBottle.setVisibility(View.VISIBLE);
				ImageView img_Throw = (ImageView) mheaderView.findViewById(R.id.iv_send_bottle);
				img_Throw.setOnClickListener(this);
				Button bt_throw = (Button)mheaderView.findViewById(R.id.bt_bottle_throw_try);
				bt_throw.setOnClickListener(this);
			}else {
				mThrowBottle.setVisibility(View.GONE);
			}
			
			if (bottlelist.getShowtips().getShow_gainbt_tips()==1) {
				mGainBottle.setVisibility(View.VISIBLE);
				ImageView img_Gain = (ImageView) mheaderView.findViewById(R.id.iv_gain_bottle);
				img_Gain.setOnClickListener(this);
				Button bt_gain = (Button)mheaderView.findViewById(R.id.bt_bottle_gain_try);
				bt_gain.setOnClickListener(this);
			}else {
				mGainBottle.setVisibility(View.GONE);
			}
			
			LoginUserInfoTable loginUserInfoTable = new LoginUserInfoTable();
			LoginUserInfoEntry loginUserInfoEntry = loginUserInfoTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid());
	
			if (loginUserInfoEntry.getBasicinfo_fullfill()==0) {
				mProfileInfo.setVisibility(View.VISIBLE);
				ImageView img_Profile = (ImageView) mheaderView.findViewById(R.id.iv_profile_info);
				img_Profile.setOnClickListener(this);
				TextView tvProfileTips = (TextView)mheaderView.findViewById(R.id.tv_bottle_profile_tips_2);
				tvProfileTips.setText(loginUserInfoEntry.getBasicinfo_tip());
			}else {
				mProfileInfo.setVisibility(View.GONE);
			}
			
			listView.addHeaderView(mheaderView);
	//		chatHistoryAdapter = new PublicActivityAdapter(this, bottlelist);
			listView.setAdapter(chatHistoryAdapter);
		}

	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case EXEU_GET_TIMELINE:
			 setAdapterForThis();
			break;
		default:
			break;
		}
		return false;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.topbar_back:
			finish();
			break;
		case R.id.topbar_menu:
			Intent intent = new Intent(this, MoreActivity.class);
			startActivity(intent);
			break;
		case R.id.iv_send_bottle:
			Intent throwIntent = new Intent(HomeOldActivity.this, ChooseBottleActivity.class);
			throwIntent.putExtra("type", "throw");
			startActivity(throwIntent);
			break;
		case R.id.iv_gain_bottle:
			Intent tryIntent = new Intent(HomeOldActivity.this, ChooseBottleActivity.class);
			tryIntent.putExtra("type", "try");
			startActivity(tryIntent);
			break;
		case R.id.iv_profile_info:
			onToast("profile");
			break;
		case R.id.iv_unlike:
			onToast("unlike");
			break;
		case R.id.iv_like:
			onToast("like");
			break;
		case R.id.bt_bottle_throw_try:
			Intent throwIntent2 = new Intent(HomeOldActivity.this, ChooseBottleActivity.class);
			throwIntent2.putExtra("type", "throw");
			startActivity(throwIntent2);
			break;
		case R.id.bt_bottle_gain_try:
			Intent tryIntent2 = new Intent(HomeOldActivity.this, ChooseBottleActivity.class);
			tryIntent2.putExtra("type", "try");
			startActivity(tryIntent2);
			break;
		default:
			break;
		}
		
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ( keyCode == KeyEvent.KEYCODE_BACK) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(getString(R.string.logout_home));
			builder.setPositiveButton(getString(R.string.confirm_ok), new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
					Process.killProcess(Process.myPid());
					System.exit(0);
				}
			});
			builder.setNegativeButton(getString(R.string.confirm_cancel), new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			builder.show();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
	
	private View mLikeView = null;
	private PopupWindow mLikePopview = null;

	/**喜欢pop*/
	private void initLikePopupWindow() {

		LayoutInflater mLayoutInflater = LayoutInflater.from(this);
		mLikeView = mLayoutInflater.inflate(R.layout.pop_bottle_like,
				null);
		ImageView iv_unlike = (ImageView)mLikeView.findViewById(R.id.iv_unlike);
		ImageView iv_like = (ImageView)mLikeView.findViewById(R.id.iv_like);
		iv_unlike.setOnClickListener(this);
		iv_like.setOnClickListener(this);
		mLikePopview = new PopupWindow(mLikeView, LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		mLikePopview.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.ic_launcher));
		mLikePopview.setOutsideTouchable(true);
		mLikePopview.update();
		mLikePopview.setTouchable(true);
		mLikePopview.setFocusable(true);
		// modifyProfile(null);

	}

	public void showInfoPopupWindow(View achorView) {
		if (mLikePopview.isShowing()) {
			mLikePopview.dismiss();
		} else {
			mLikePopview.showAtLocation(achorView, Gravity.RIGHT, 0, 0);
//			mLikePopview.showAsDropDown(achorView);
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		boolean needRefresh = getIntent().getBooleanExtra("need_refresh", false);
		if (needRefresh) {
			//TODO 需要刷新
		}
	}
	
}
